package com.wwwarehouse.contract.contract.modify;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.fingerprints.service.IFingerprintClient;
import com.wwwarehouse.common.BuildConfig;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.adapter.pop.BubblePopAdapter;
import com.wwwarehouse.common.bean.filter.FilterBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.common.Common;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tools.rsa.StringUtils;
import com.wwwarehouse.contract.bean.ContractChooseGoodsBean;
import com.wwwarehouse.contract.bean.ResourceItemBean;
import com.wwwarehouse.contract.bean.SettingRuleBean;
import com.wwwarehouse.contract.common.ContractCommon;
import com.wwwarehouse.contract.contract.MyBaseViewPagerFragment;
import com.wwwarehouse.contract.contract.ReleaseGoodsListFragment;
import com.wwwarehouse.contract.contract.ReleaseSettingPublishingRulesFragment;
import com.wwwarehouse.contract.core.BindEventBus;
import com.wwwarehouse.contract.core.ContractConstant;
import com.wwwarehouse.contract.core.ContractEventCode;
import com.wwwarehouse.contract.event.ContractEvent;
import com.wwwarehouse.contract.event.CountEvent;
import com.wwwarehouse.contract.event.DeleteEvent;
import com.wwwarehouse.contract.event.ReleaseEvent;
import com.wwwarehouse.contract.event.UpdateShoppingCardEvent;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.amap.api.mapcore.util.db.C;

/**
 * @author Joseph on 2017/10/19.
 *         <p/>
 *         浏览商品
 */
@BindEventBus
public class ChooseGoodsViewPagerFragment extends MyBaseViewPagerFragment {

	private List<FilterBean> sortList; //排序
	private boolean isShow = true;
	private String mSort = "create_time desc";
	private String pbUkid;
	private String buId;
	private String text;
	private String mContractUkid;
	private String mSupplierBusinessId;

	private int select;
	private List<ContractChooseGoodsBean.ListBean> selectTag;

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if (ContractCommon.getInstance().getModifyPublishGoodsData() != null && ContractCommon.getInstance().getModifyPublishGoodsData().size() > 0) {
			ContractCommon.getInstance().getModifyPublishGoodsData().clear();
		}
		return super.onCreateView(inflater, container, savedInstanceState);
	}

	@Override
	public void setTitle() {
		if (peekFragment() instanceof ChooseGoodsViewPagerFragment) {
			mActivity.setTitle("选择商品");
		}
	}

	@Override
	public void requestDatas() {
		ContractCommon.getInstance().getModifyPublishGoodsData().clear();
		sortList = new ArrayList<>();
		sortList.add(new FilterBean(true, "更新时间由近到远")); //默认排序
		sortList.add(new FilterBean(false, "更新时间由远到近"));
		if (getArguments() == null || getArguments().getString(ContractConstant.KEY_MODIFY_PAYMENT_ITEM_CONTRACT_UKID) == null || getArguments().getString(ContractConstant.KEY_SUPPLIER_BUSINESSID) == null) {
			mLoadingView.showEmptyView(true);
			mLoadingView.setEmptyListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					requestDatas();
				}
			});
			return;
		}
		mContractUkid = getArguments().getString(ContractConstant.KEY_MODIFY_PAYMENT_ITEM_CONTRACT_UKID);
		mSupplierBusinessId = getArguments().getString(ContractConstant.KEY_SUPPLIER_BUSINESSID);
		mConfirmBtn.setVisibility(View.GONE);
		mConfirmBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//保存选择资源
				((BaseCardDeskActivity) mActivity).hideSearchTitle();
				//更改点：  这里不请求接口了，直接从本地带过去
				AddedSettingPublishingRulesFragment rulesFragment = new AddedSettingPublishingRulesFragment();
				Bundle bundle = new Bundle();
				bundle.putString("pbUkid", pbUkid); //  发布ukid
				bundle.putString("sort", mSort); //   排序(DESC,ASC)
				List<ContractChooseGoodsBean.ListBean> listBeen = ContractCommon.getInstance().getModifyPublishGoodsData();
				if (listBeen == null || listBeen.size() == 0) {
					toast("数据为空");
					return;
				}
				List<SettingRuleBean.DataBean.ListBean> list = convertList(listBeen);
				if (list == null || list.size() == 0) {
					toast("数据为空");
					return;
				}
				bundle.putSerializable("select_list", (Serializable) list);
				bundle.putString(ContractConstant.KEY_MODIFY_PAYMENT_ITEM_CONTRACT_UKID , mContractUkid);
				rulesFragment.setArguments(bundle);
				pushFragment(rulesFragment);
			}
		});
		requestData();

	}

	private void requestData() {
		Map<String, Object> map = new HashMap<>();
		map.put("supplierBusinessId", mSupplierBusinessId); //   业务单位ID(必填)
		map.put("page", "1"); //
		map.put("contractUkid", mContractUkid); //  发布ukid
		map.put("rsName", ""); // 资源名称
		map.put("sort", mSort); //     排序(DESC,ASC)
		httpPost(ContractConstant.METHOD_MODIFY_GET_RESOURCE_ITEM, map, 0, false, "");
	}

	public void onEventMainThread(Object event) {
		if (event instanceof ReleaseEvent) {
			if (((ReleaseEvent) event).getMsg().equals("notify")) {
				if (((ReleaseEvent) event).getCode() == ReleaseEvent.RELEASE_SELECT_GOODS) {
					int selectTagCount = getSelectTag().size();
					mConfirmBtn.setVisibility(ContractCommon.getInstance().getModifyPublishGoodsData().size() > 0 ? View.VISIBLE : View.GONE);
					mConfirmBtn.setText(ContractCommon.getInstance().getModifyPublishGoodsData().size()+ "");
				}
			}
		} else if (event instanceof DeleteEvent) {
			requestData();
		} else if (event instanceof CountEvent) {
			select = ((CountEvent) event).getCount();
			mConfirmBtn.setVisibility(select > 0 ? View.VISIBLE : View.GONE);
			mConfirmBtn.setText(select + "");
		}
	}

	@Override
	public void sortClick(View anchor) {
		//排序
		if (peekFragment() instanceof ChooseGoodsViewPagerFragment) {
			PopUpUtils.showBubbleDown(anchor, mActivity, sortList, new BubblePopAdapter.OnPopListClickListener() {
				@Override
				public void setOnItemClickListener(int i, View view) {
					if (i == 0) {
						mSort = "create_time desc";      //时间正序
						sortList.get(0).setSelect(true);
						sortList.get(1).setSelect(false);

					} else if (i == 1) {
						mSort = "create_time asc";        //时间倒序
						sortList.get(0).setSelect(false);
						sortList.get(1).setSelect(true);

					}
					requestData();

				}
			});
		}


	}

	@Override
	public void searchNoRealTimeClick(String text) {
		if (peekFragment() instanceof ChooseGoodsViewPagerFragment) {
			selectTag =ContractCommon.getInstance().getModifyPublishGoodsData();
			this.text = text;
			Map<String, Object> map = new HashMap<>();
			map.put("supplierBusinessId", mSupplierBusinessId); //   业务单位ID(必填)
			map.put("page", "1"); //
			map.put("contractUkid", mContractUkid); //  发布ukid
			map.put("rsName", text); // 资源名称
			map.put("sort", mSort); //     排序(DESC,ASC)
			httpPost(ContractConstant.METHOD_MODIFY_GET_RESOURCE_ITEM, map, 2, true, "");
		}


	}


	@Override
	public void cancelClick() {
		if (peekFragment() instanceof ChooseGoodsViewPagerFragment) {
			selectTag = ContractCommon.getInstance().getModifyPublishGoodsData();
			mConfirmBtn.setVisibility(selectTag.size() > 0 ? View.VISIBLE : View.GONE);
			mCustomPager.setVisibility(View.VISIBLE);
			mEmptyLayout.setVisibility(View.GONE);
			requestData();
		}

	}

	//获取选择的数据集合
	private List<ContractChooseGoodsBean.ListBean> getSelectTag() {
		List<ContractChooseGoodsBean.ListBean> selectDatas = new ArrayList<>();
		for (int i = 0; i < fragmentList.size(); i++) {
			if (fragmentList.get(i) != null) {
				ChooseGoodsListFragment currentFragment = (ChooseGoodsListFragment) fragmentList.get(i);
				if (currentFragment.mAdapter != null) {
					List<ContractChooseGoodsBean.ListBean> selectData = currentFragment.mAdapter.getSelectData();
					selectDatas.addAll(selectData);
				}
			}
		}
		return selectDatas;
	}

	@Override
	public void onSuccess(CommonClass commonClass, int what) {
		LogUtils.showLog("个数是-------------》" + ContractCommon.getInstance().getModifyPublishGoodsData().size() + "");

		if (what == 0) {
			if (TextUtils.equals("0", commonClass.getCode())) {
				ContractChooseGoodsBean dataBean = JSON.parseObject(commonClass.getData().toString(), ContractChooseGoodsBean.class);
				if (dataBean ==null || dataBean.getList() == null || dataBean.getList().size() == 0) {
					ShowEmptyGoodsView();
					mConfirmBtn.setVisibility(View.GONE);
				} else {
					mCustomPager.setVisibility(View.VISIBLE);
					mEmptyLayout.setVisibility(View.GONE);
					if (selectTag != null) {
						HashSet<ContractChooseGoodsBean.ListBean> listBeen = new HashSet<>(selectTag);
						mConfirmBtn.setVisibility(listBeen.size() > 0 ? View.VISIBLE : View.GONE);
					}
					Bundle bundle = new Bundle();
					bundle.putString("supplierBusinessId", mSupplierBusinessId); //   业务单位ID(必填)
					bundle.putString("contractUkid", mContractUkid); //  发布ukid
					bundle.putString("rsName", ""); // 资源名称
					bundle.putString("sort", mSort); //     排序(DESC,ASC)
					bundle.putSerializable("selectTag", (Serializable) selectTag);
					bundle.putSerializable("data", dataBean);
					SetFragmentAndPage(dataBean.getList().size(), 5, ChooseGoodsListFragment.class.getName(), bundle);
				}
			} else {
				toast(commonClass.getMsg());
			}
		} else if (what == 1) {

			if (TextUtils.equals("0", commonClass.getCode())) {
				ContractCommon.getInstance().getModifyPublishGoodsData().clear();
				ReleaseSettingPublishingRulesFragment rulesFragment = new ReleaseSettingPublishingRulesFragment();
				Bundle bundle = new Bundle();
				bundle.putString("contractUkid", mContractUkid); //  发布ukid
				bundle.putString("sort", mSort); //   排序(DESC,ASC)
				rulesFragment.setArguments(bundle);
				pushFragment(rulesFragment);
				requestData();
			} else {
				toast(commonClass.getMsg());
			}
		} else if (what == 2) {
			ContractChooseGoodsBean dataBean = JSON.parseObject(commonClass.getData().toString(), ContractChooseGoodsBean.class);
			if (dataBean ==null || dataBean.getList() == null || dataBean.getList().size() == 0) {
				ShowEmptyView();
				mConfirmBtn.setVisibility(View.GONE);
				if (mPagerInternal.getVisibility() == View.VISIBLE) {
					mPagerInternal.setVisibility(View.GONE);
				}
			} else {
				mCustomPager.setVisibility(View.VISIBLE);
				mEmptyLayout.setVisibility(View.GONE);
				if (selectTag != null) {
					HashSet<ContractChooseGoodsBean.ListBean> listBeen = new HashSet<>(selectTag);
					mConfirmBtn.setVisibility(listBeen.size() > 0 ? View.VISIBLE : View.GONE);
				}
				Bundle bundle = new Bundle();
				bundle.putString("supplierBusinessId", mSupplierBusinessId); //   业务单位ID(必填)
				bundle.putString("contractUkid", mContractUkid); //  发布ukid
				bundle.putString("rsName", ""); // 资源名称
				bundle.putString("sort", mSort); //     排序(DESC,ASC)
				bundle.putSerializable("selectTag", (Serializable) selectTag);
				bundle.putSerializable("data", dataBean);
				SetFragmentAndPage(dataBean.getList().size(), 5, ChooseGoodsListFragment.class.getName(), bundle);
			}
		}


	}

	@Override
	public void onDownPull() {
		if (isShow) {
			((BaseCardDeskActivity) mActivity).hideFilterBt();
			((BaseCardDeskActivity) mActivity).showSearchTitle();
		} else {
			((BaseCardDeskActivity) mActivity).hideSearchTitle();
		}
		isShow = !isShow;
	}

	/**
	 * 自己拼装成一个想要的List
	 *
	 * @param listBean
	 */
	private List<SettingRuleBean.DataBean.ListBean> convertList(List<ContractChooseGoodsBean.ListBean> listBean) {
		List<SettingRuleBean.DataBean.ListBean> resultList = new ArrayList<>();
		try {
			if (listBean == null || listBean.size() == 0) {
				return null;
			}
			for (int i = 0; i < listBean.size(); i++) {
				SettingRuleBean.DataBean.ListBean bean = new SettingRuleBean.DataBean.ListBean();
				bean.setDefinedUkid(String.valueOf(listBean.get(i).getDefinedUkid()));
				if (StringUtils.isNoneNullString(listBean.get(i).getDefinedName())) {
					bean.setName(listBean.get(i).getDefinedName());
				}
				if (listBean.get(i).getMediaList() != null && listBean.get(i).getMediaList().size() > 0 && StringUtils.isNoneNullString(listBean.get(i).getMediaList().get(0).getRelatedUrl())) {
					bean.setImg(listBean.get(i).getMediaList().get(0).getRelatedUrl());
				}
				if (StringUtils.isNoneNullString(listBean.get(i).getUnitName())) {
					bean.setUnit(listBean.get(i).getUnitName());
					bean.setPbQtyUnit(listBean.get(i).getUnitName());
				}
				bean.setPbQtyUnitUkid(String.valueOf(listBean.get(i).getUnitUkid()));
				if (listBean.get(i).getIdentifyList() != null && listBean.get(i).getIdentifyList().size() > 0 && StringUtils.isNoneNullString(listBean.get(i).getIdentifyList().get(0).getIdentifyCode())) {
					bean.setBarCode(listBean.get(i).getIdentifyList().get(0).getIdentifyCode());
				}
				resultList.add(bean);
			}
			return resultList;
		} catch (Exception e) {
			e.printStackTrace();
			return resultList;
		}
	}

	@Override
	protected void receiveEvent(ContractEvent contractEvent) {
		if (contractEvent.getCode() == ContractEventCode.CODE_REFRESH_MODIFY_PUBLISH_GOODS_SHOPPING_CARD) {
			UpdateShoppingCardEvent event = (UpdateShoppingCardEvent) contractEvent.getData();
			if (event == null || event.getmSelectList() == null) {
				requestData();
				return;
			}
			List<SettingRuleBean.DataBean.ListBean> list = event.getmSelectList();
			if (list == null) {
				requestData();
				return;
			}
			//返回更新购物车里的数量
			if (list.size() == 0) {
				ContractCommon.getInstance().getModifyPublishGoodsData().clear();
				selectTag = new ArrayList<>();
				mConfirmBtn.setVisibility(selectTag.size() > 0 ? View.VISIBLE : View.GONE);
				mConfirmBtn.setText(selectTag.size() + "");
				requestData();
				return;
			}
			List<ContractChooseGoodsBean.ListBean> resultList = convertReturnList(list);
			if (resultList == null || resultList.isEmpty()) {
				requestData();
				return;
			}
			ContractCommon.getInstance().getModifyPublishGoodsData().clear();
			ContractCommon.getInstance().setModifyPublishGoodsData(resultList);
			selectTag = resultList;
			mConfirmBtn.setVisibility(selectTag.size() > 0 ? View.VISIBLE : View.GONE);
			mConfirmBtn.setText(selectTag.size() + "");
			requestData();


		}

	}

	/**
	 * 再转换回来
	 *
	 * @param listBean
	 */
	private List<ContractChooseGoodsBean.ListBean> convertReturnList(List<SettingRuleBean.DataBean.ListBean> listBean) {
		List<ContractChooseGoodsBean.ListBean> resultList = new ArrayList<>();
		try {
			if (listBean == null || listBean.size() == 0) {
				return null;
			}
			for (int i = 0; i < listBean.size(); i++) {
				ContractChooseGoodsBean.ListBean bean = new ContractChooseGoodsBean.ListBean();
				bean.setDefinedUkid(Long.valueOf(listBean.get(i).getDefinedUkid()));
				if (StringUtils.isNoneNullString(listBean.get(i).getName())) {
					bean.setDefinedName(listBean.get(i).getName());
				}
				List<ContractChooseGoodsBean.ListBean.MediaListBean> mediaList = new ArrayList<>();
				if (StringUtils.isNoneNullString(listBean.get(i).getImg())) {
					ContractChooseGoodsBean.ListBean.MediaListBean mediaBean = new ContractChooseGoodsBean.ListBean.MediaListBean();
					mediaBean.setRelatedUrl(listBean.get(i).getImg());
					mediaList.add(mediaBean);
					bean.setMediaList(mediaList);
				}

				if (StringUtils.isNoneNullString(listBean.get(i).getUnit())) {
					bean.setUnitName(listBean.get(i).getUnit());
				}
				if (StringUtils.isNoneNullString(listBean.get(i).getPbQtyUnitUkid())) {
					bean.setUnitUkid(Long.valueOf(listBean.get(i).getPbQtyUnitUkid()));
				}
				List<ContractChooseGoodsBean.ListBean.IdentifyListBean> identifyList = new ArrayList<>();
				if (StringUtils.isNoneNullString(listBean.get(i).getBarCode())) {
					ContractChooseGoodsBean.ListBean.IdentifyListBean identifyBean = new ContractChooseGoodsBean.ListBean.IdentifyListBean();
					identifyBean.setIdentifyCode(listBean.get(i).getBarCode());
					identifyList.add(identifyBean);
					bean.setIdentifyList(identifyList);
				}
				resultList.add(bean);
			}
			return resultList;
		} catch (Exception e) {
			e.printStackTrace();
			return resultList;
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		((BaseCardDeskActivity) mActivity).showFilterBt();
	}
}
